package net.thxjj.mobileServer.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.thxjj.mobileServer.controller.base.BaseController;
import net.thxjj.mobileServer.entity.*;
import net.thxjj.mobileServer.service.impl.GenieService;
import net.thxjj.mobileServer.service.impl.UserService;
import net.thxjj.mobileServer.util.ParameterMap;
import net.thxjj.mobileServer.util.Tools;
import net.thxjj.sitermodel.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName:AligenieController
 * @Description:TODO
 * @Autor:TracyHenry
 * @Date:2022/12/18 0018
 * @Version:1.0
 **/
@Slf4j
@Controller
@RequestMapping("/genie")
public class AligenieController extends BaseController {

    private static final String REDICT_URI= "REDICT_URI";
    private static final String CLIENT_ID= "CLIENT_ID";
    private static final String STATUS= "STATUS";
    private static final String RESPONSE_TYPE= "RESPONSE_TYPE";

    @Autowired
    private GenieService iGenieService;

    @Autowired
    private UserService iUserService;


    /**
     * aws token test
     * @return
     */
    @RequestMapping(value="/tokenTest",method= RequestMethod.POST)
    @ResponseBody
    public Object tokenTest(@RequestBody JSONObject jsonObject)  {

        String topic =  this.getRequest().getHeader("topic");
        log.info("topic:"+topic);
        String tokentest = this.getParameterMap().toString();

        log.info("jsonObject:"+jsonObject.toString());
        log.info("TokenTest:"+tokentest);

        return  ResponseModel.getModel(ResultEnum.SUCCESS,null);

    }

    /**
     * 登录页面授权
     * @return
     */
    @RequestMapping(value="/tologin",method= RequestMethod.GET)
    public Object tologin() throws UnsupportedEncodingException {


        String encode_redict_uri = this.getParameterMap().getString("redirect_uri");
        String redict_uri = URLDecoder.decode(encode_redict_uri,"utf-8");
        String status = this.getParameterMap().getString("state");
        String response_type = this.getParameterMap().getString("response_type");
        String client_id = this.getParameterMap().getString("client_id");
        this.getSession().setMaxInactiveInterval(1800);
        this.getSession().setAttribute(REDICT_URI,redict_uri);
        this.getSession().setAttribute(CLIENT_ID,client_id);
        this.getSession().setAttribute(STATUS,status);
        this.getSession().setAttribute(RESPONSE_TYPE,response_type);


        return "page/login";

    }

    /**
     * login
     * @return
     * h5授权登录接口
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Object login(){

        String redict_uri = (String)this.getSession().getAttribute(REDICT_URI);
        String client_id = (String)this.getSession().getAttribute(CLIENT_ID);
        String status = (String)this.getSession().getAttribute(STATUS);
        String response_type = (String)this.getSession().getAttribute(RESPONSE_TYPE);

        if(Tools.isEmpty(redict_uri)||Tools.isEmpty(client_id)||Tools.isEmpty(status)||Tools.isEmpty(response_type)){
            return ResponseModel.getModel(GenieErrcode.PARAMETER_EMPTY,null);
        }

        if(!GenieResum.CLINET_ID.equals(client_id)){
            return ResponseModel.getModel(GenieErrcode.CLIENT_ID_NOT_CORRECT,null);
        }

        if(!"code".equals(response_type)){
            return ResponseModel.getModel(GenieErrcode.PARAMETER_ERROR,null);
        }

        String username = this.getParameterMap().getString("username");
        String password = this.getParameterMap().getString("password");

        return iGenieService.loginOauthGenie(username,password,redict_uri);
    }


    /**
     * 供天猫精灵获取access_token和refresh_token
     * @return
     */
    @RequestMapping(value="/token",method= RequestMethod.POST)
    @ResponseBody
    public Object token()  {

        String grant_type = this.getParameterMap().getString("grant_type");
        String client_id = this.getParameterMap().getString("client_id");
        String client_secret = this.getParameterMap().getString("client_secret");
        String code = this.getParameterMap().getString("code");

        if(Tools.isEmpty(grant_type)||Tools.isEmpty(client_id)||Tools.isEmpty(client_secret)||Tools.isEmpty(code)){
            return ResponseModel.getGenieErrorCode(GenieErrcode.PARAMETER_EMPTY);
        }

        if(!GenieResum.CLINET_ID.equals(client_id)){
            return ResponseModel.getGenieErrorCode(GenieErrcode.CLIENT_ID_NOT_CORRECT);
        }

        if(!GenieResum.CLINET_SECRET.equals(client_secret)){
            return ResponseModel.getGenieErrorCode(GenieErrcode.CLIENT_SECRET_NOT_CORRECT);
        }

        if(!"authorization_code".equals(grant_type)&&!"refresh_token".equals(grant_type)){
            return ResponseModel.getGenieErrorCode(GenieErrcode.PARAMETER_ERROR);
        }

        GenieOauthBean genieOauthBean = iGenieService.getGenieOauthBeanCode(code,null);
        if(genieOauthBean==null){
            return ResponseModel.getGenieErrorCode(GenieErrcode.CODE_IS_NOT_EXIST);
        }

        long login_time = genieOauthBean.getLoginTime();

        long refresh_time = genieOauthBean.getRefreshTime();

         long cur_time = System.currentTimeMillis();

         if(cur_time>(refresh_time+GenieResum.ACCESS_TOKEN_EXPIRED_SECOND)){
             return ResponseModel.getGenieErrorCode(GenieErrcode.ACCESS_TOKEN_IS_EXSPIRED);
         }

         if(cur_time>(login_time+GenieResum.REFRESH_TOKEN_EXPIRED_SECOND)){
             return ResponseModel.getGenieErrorCode(GenieErrcode.REFRESH_TOKEN_IS_EXSPIRED);
         }



        return iGenieService.updateAccessToken(grant_type,genieOauthBean);

    }


    /**
     * 供天猫精灵网关控制同步数据以及远程控制
     * @return
     */
    @RequestMapping(value="/control",method= RequestMethod.POST)
    @ResponseBody
    public Object control(@RequestBody JSONObject jsonObject)  {

        log.info("插座控制:"+jsonObject.toJSONString());


        JSONObject header = jsonObject.getJSONObject("header");
        String c_type = header.getString("namespace");

        JSONObject payload =jsonObject.getJSONObject("payload");
        String access_token = payload.getString("accessToken");



        long cur_time = System.currentTimeMillis();
        GenieOauthBean genieOauthBean = iGenieService.getGenieOauthBean(access_token);
       if(genieOauthBean==null || cur_time>(genieOauthBean.getRefreshTime()+GenieResum.ACCESS_TOKEN_EXPIRED_SECOND)){
           header.put("name","ErrorResponse");
           HashMap<String,Object> result = ResponseModel.getGenieErrorCode(header,null, GenieControlErrcode.ACCESS_TOKEN_INVALIDATE);

           log.info("返回:"+result.toString());

           return result;
       }

        if(payload.containsKey("deviceIds")){
            JSONArray jsonArray_devs = payload.getJSONArray("deviceIds");
            List<String> devices_exist = iGenieService.getDeviceList(genieOauthBean.getUserId());
            if(!devices_exist.contains(jsonArray_devs.getString(0))){
                header.put("name","ErrorResponse");
                HashMap<String,Object> result = ResponseModel.getGenieErrorCode(header,jsonArray_devs.getString(0), GenieControlErrcode.DEVICE_IS_NOT_EXIST);

                log.info("返回:"+result.toString());

                return result;
            }
        }



        if("AliGenie.Iot.Device.Discovery".equals(c_type)){
            header.put("name","DiscoveryDevicesResponse");
            HashMap<String,Object> result = new HashMap<>();
            result.put("header",header);



            List<String> listActions = new ArrayList<>();
            listActions.add("TurnOn");
            listActions.add("TurnOff");

            List<HashMap<String,Object>> list_device = new ArrayList<>();


           List<Device>  deviceBeans = iUserService.getBindDeviceList(genieOauthBean.getUserId());

           for (int i=0;i<deviceBeans.size();i++){
               HashMap<String,Object> devicemap = new HashMap<>();
               devicemap.put("deviceId",deviceBeans.get(i).getDeviceId());
               devicemap.put("deviceName",deviceBeans.get(i).getDeviceName());
               devicemap.put("deviceType","outlet");
               devicemap.put("zone","");
               devicemap.put("brand","涂鸦·Tuya");
               devicemap.put("model","123");
               devicemap.put("icon","https://121.199.61.205:1416/upload/show/user/socket.png");


               ParameterMap p = new ParameterMap();
               p.put("name","powerstate");
               p.put("value", iGenieService.getPowerState(deviceBeans.get(i).getDeviceId())==1?"on":"off");
               List<ParameterMap> listp = new ArrayList<>();
               listp.add(p);


               devicemap.put("properties",listp);
               devicemap.put("actions",listActions);
               list_device.add(devicemap);
           }

            HashMap<String,Object> payload2 = new HashMap<>();
            payload2.put("devices",list_device);
            result.put("payload",payload2);

            log.info("返回:"+result.toString());
            return result;
        }else if("AliGenie.Iot.Device.Control".equals(c_type)){


            JSONArray jsonArray_devs = payload.getJSONArray("deviceIds");
            JSONArray responseList = new JSONArray();
            for (int i=0;i<jsonArray_devs.size();i++){
                String deviceId = jsonArray_devs.getString(i);
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("errorCode","SUCCESS");
                jsonObject1.put("message","SUCCESS");
                jsonObject1.put("deviceId",deviceId);
                responseList.add(jsonObject1);
            }


            HashMap<String,Object> result = new HashMap<>();
            result.put("header",header);
            payload.put("deviceResponseList",responseList);
            result.put("payload",payload);

            log.info("返回:"+result.toString());

           String cmd = "{\"msgId\":1,\"action\":\"appSend\",\"params\":{\"devTid\":\"ESP_e8db8494f1a4\",\"ctrlKey\":\"9a9e03e7ecc8e572c183c6af18b6d44a\",\"data\":{\"cmdId\":2,\"cur\":33,\"vol\":100,\"name\":\"haha\"}}}";
            JSONObject jsonObject22 = new JSONObject();
            jsonObject22.put("user_id",genieOauthBean.getUserId());
            jsonObject22.put("info",cmd);


            return result;
        }
        else {

            header.put("name","ErrorResponse");

            HashMap<String,Object> result = ResponseModel.getGenieErrorCode(header,null, GenieControlErrcode.SERVICE_ERROR);

            log.info("返回:"+result.toString());

            return result;
        }


    }


}
